import { Ref, ref } from 'vue'
import { watch } from 'vue'
import { useLoginer } from './loginer'
import axios from '/@/api/axios'

export function useIsTested({ projectId }: { projectId: Ref<number> }) {
  const isTested = ref(false)

  const { loginer } = useLoginer()

  const userProjectId = ref('')

  const promise = ref<Promise<any>>()

  watch(
    projectId,
    async (pid) => {
      if (!pid) {
        return
      }
      getData(pid)
    },
    { immediate: true }
  )

  async function getData(pid: number) {
    promise.value = getProjectList(Number(loginer.value.id), pid)

    const {
      data: {
        data: { records },
      },
    } = await promise.value

    isTested.value = records.length > 0

    if (isTested.value) {
      userProjectId.value = records[0].id
    }
  }

  return {
    isTested,
    promise,
  }
}

function getProjectList(userId: number, projectId: number) {
  const url = `/api/blade-measure/measure/userprojectgauge/page?current=1&size=500&includeId=${userId}&projectId=${projectId}`

  return axios.get(url)
}
